<?php 
namespace Utuo;

class LoginLog {
	
	private $config = array(
		'LogTableName' => '', # 日志表名
		'authField' => '', # 管理帐户/合作商/客户id在日志表中的字段名称
	);
	
	public static function getInstance( $config ) {
		static $loginLog = null;
		if ( !$loginLog ) {
			$loginLog = new LoginLog( $config );
		}
		return $loginLog;
	}
	
	public function __construct( $config = array() ) {
		$config['authField'] or $config['authField']  = C('AUTH_FIELD');
		$config['LogTableName'] or $config['LogTableName']  = C('LOGIN_LOG_TABLE');
		$config and $this->config = array_merge($this->config, $config);
	}
	
	/**
	 * 登录日志
	 * array(
	 * 	 'id' => '', # 管理帐户/合作商/客户id
	 * 	 'admin_id' => '', # 管理员id
	 *   'session_id' => '', # 会话id
	 * )
	 * @param unknown $data
	 */
	public function log( $data ) {
		$now = time();
		M($this->LogTableName)->where(array( 'admin_id' => $data['admin_id'], 'loginout_time' => 0, ))->save(array('loginout_time'=>array('exp', 'last_activity_time')));
		M($this->LogTableName)->add(array(
			"{$this->authField}" => $data['id'], // 用户id
			'admin_id' => $data['admin_id'], // 管理员id
			'session_id' => $data['session_id'],
			'ip' => get_client_ip(),
			'login_time' => $now,
			'last_activity_time' => $now,
			'loginout_time' => 0,
			'create_time' => $now,
		));
	}
	
	/**
	 * 活动更新
	 * array(
	 * 	 'admin_id' => '', # 管理员id
	 *   'session_id' => '', # 会话id
	 * )
	 * @param unknown $data
	 */
	public function active( $data ) {
		$lastActive = M("PartnerLoginLog")->where(array(
			'admin_id' => $data['admin_id'],
			'session_id' => session_id(),
			'loginout_time' => 0,
		))->save(array('last_activity_time' => time()));
	}
	
	/**
	 * 登录日志
	 * array(
	 * 	 'admin_id' => '', # 管理员id
	 *   'session_id' => '', # 会话id
	 * )
	 * @param unknown $data
	 */
	public function out( $data ) {
		$now = time();
		$lastActive = M("PartnerLoginLog")->where(array(
			'admin_id' => $data['admin_id'],
			'session_id' => $data['session_id'],
			'loginout_time' => 0,
		))->save(array('loginout_time' => $now));
	}
	
	public function __get( $name ) {
		return $this->config[$name];
	}
	
	public function __set( $name, $value ) {
		$this->config[$name] = $value;
	}
	
}